<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Department;
use App\Models\Staff;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Http\response;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class StaffController extends Controller {
	/**
	 * Create a new controller instance.
	 *
	 * @return void
	 */

	private $user_id;
	public function __construct() {
		parent::__construct();
		$this->user_id = Auth::id();
	}
	//新增保存
	public function add(Request $request) {
		$type = $request->input('type');
		$name = $request->input('name');
		$mobile = $request->input('mobile');
		$deptId = $request->input('deptId');
		if (empty($name) || empty($mobile) || empty($deptId)) {
			return $this->respond('empty_error');
		}
		$com = DB::table('cmpInfo')->where('userId', $this->user_id)->select('id', 'userId')->first();
		if (empty($com)) {
			return response()->json(['code' => 500, 'msg' => '请先完善公司信息']);
		}
		$m = Staff::where(['cmpId' => $com->id, 'mobile' => $mobile])->first();
		if (!empty($m)) {
			if ($m->status == 0) {
				return response()->json(['code' => 500, 'msg' => '新增失败,手机号不能重复！']);
			}
		} else {
			$m = new Staff();
		}
		$m->cmpId = $com->id;
		$m->deptId = $deptId;
		$m->name = $name;
		$m->mobile = $mobile;
		$m->type = $type;
		$m->status = 0;
		$m->email = $request->input('email');
		$m->position = $request->input('position');
		$m->employeeNo = $request->input('employeeNo');
		$m->entryTime = $request->input('entryTime');
		$m->remarks = $request->input('remarks');
		$result = $m->save();
		if ($result) {
			return $this->respond('add_ok');
		}
		return $this->respond('add_error');
	}
	//获取单条记录
	public function get($id) {
		$data = Staff::find($id);
		if (!empty($data)) {
			return $this->respond('get_ok', $data);
		}
		return $this->respond('get_error');
	}
	//更新保存
	public function put(Request $request, $id) {
		if (empty($id)) {
			return $this->respond('empty_error');
		}

		$model = new Staff();
		$m = $model::find($id);
		if (empty($m)) {
			return $this->respond('get_error');
		}
		$name = $request->input('name');
		$mobile = $request->input('mobile');
		if (empty($name) || empty($mobile)) {
			return $this->respond('empty_error');
		}
		$check_status = Staff::where(['status' => 0, 'cmpId' => $m->cmpId, 'mobile' => $mobile])->where('id', '!=', $id)->first();
		if (!empty($check_status)) {
			return response()->json(['code' => 500, 'msg' => '更新失败,手机号不能重复！']);
		}
		$check_del = Staff::where(['status' => 1, 'cmpId' => $m->cmpId, 'mobile' => $mobile])->where('id', '!=', $id)->first();
		if (!empty($check_del)) {
			return response()->json(['code' => 500, 'msg' => '手机号已被占用，请输入正确的手机号或删除当前用户重新添加']);
		}
		$m->name = $name;
		$m->mobile = $mobile;
		$m->type = $request->input('type');
		$m->email = $request->input('email');
		$m->position = $request->input('position');
		$m->employeeNo = $request->input('employeeNo');
		$m->entryTime = $request->input('entryTime');
		$m->remarks = $request->input('remarks');
		$result = $m->save();
		if ($result) {
			return $this->respond('update_ok');
		}
		return $this->respond('update_error');
	}
	//删除员工
	public function remove(Request $request) {
		$id = $request->input('id');
		if (empty($id)) {
			return $this->respond('empty_error');
		}
		$id_arr = explode(',', $id);
		$result = Staff::whereIn('id', $id_arr)->update(['status' => 1]);
		if ($result) {
			return $this->respond('delete_ok');
		}
		return $this->respond('delete_error');
	}

	public function moveStaff(Request $request) {
		$node_ids = [];
		$id = $request->input('id');
		$deptId = $request->input('deptId');
		if (empty($deptId) || empty($deptId)) {
			return $this->respond('empty_error');
		}
		if (empty($id) || !is_array($id)) {
			return $this->respond('empty_error');
		}
		$model = Staff::whereIn('id', $id)->get();
		if (empty($model)) {
			return $this->respond('get_error');
		}
		$pnode = Department::where(['userId' => $this->user_id, 'depth' => 1])->first();
		$childs = $pnode->getDescendantsAndSelf(['id as deptId']);
		if (!empty($childs)) {
			$arr = $childs->toArray();
			$ids = array_column($arr, 'deptId');
			if (in_array($deptId, $ids)) {
				$result = Staff::whereIn('id', $id)->update(['deptId' => $deptId]);
				if ($result) {
					return $this->respond('update_ok');
				}
				return $this->respond('update_error');
			}
			return response()->json(['code' => 500, 'msg' => '不能将员工移动到该部门下面']);
		}
	}
	public function export(Request $request) {
		$title = "员工信息表" . time();
		$deptId = $request->input('deptId');
		if (empty($deptId)) {
			return $this->respond('empty_error');
		}
		$node = Department::find($deptId);
		if (empty($node)) {
			return $this->respond('get_error');
		}
		$id_str = $node->getDescendantsAndSelf(['id as deptId']);
		$data = DB::table('employeeInfo')->whereIn('deptId', $id_str)->where('status', 0)->get();
		if (empty($data)) {
			return response()->json(['code' => 500, 'msg' => '数据为空不能导出']);
		}
		$cellData = [['姓名', '手机号', '邮箱', '职位', '工号', '入职日期', '备注', '创建时间']];
		foreach ($data as $key => $value) {
			$get_date = date('Y-m-d H:i:s', $value->createdAt);
			$entryTime = "";
			if (!empty($value->entryTime)) {
				$entryTime = date('Y-m-d', $value->entryTime);
			}
			$cellData[$key + 1] = [
				$value->name, $value->mobile, $value->email, $value->position,
				$value->employeeNo, $entryTime, $value->remarks, $get_date,
			];
		}
		Excel::create($title, function ($excel) use ($cellData) {
			$excel->sheet('Sheet', function ($sheet) use ($cellData) {
				$sheet->rows($cellData);    
			});
		})->store('xls', 'uploads/excel');     
		$path['filepath'] = '/uploads/excel/' . $title . '.xls';
		return response()->json(['code' => 200, 'msg' => '导出数据成功', 'data' => $path]);
	}
	public function import(Request $request) {
		$deptId = $request->input('deptId');
		$file = $request->file('file');
		if (empty($file) || empty($deptId)) {
			return $this->respond('empty_error');
		}
		// 获取文件后缀名
		$exe = $file->getClientOriginalExtension();
		$exe = strtolower($exe);
		if (!in_array($exe, ['xls', 'xlsx'])) {
			return response()->json(array('code' => 500, 'msg' => '请上传后缀名为xls、xlsx的文件'));
		}
		$res = [];
		$data = [];
		Excel::load($file, function ($reader) use (&$res) {
			$reader->ignoreEmpty();
			$reader = $reader->getSheet(0);
			$res = $reader->toArray();
		}, 'UTF-8');
		$company = Company::where('userId', $this->user_id)->first();
		if (empty($company)) {
			return response()->json(['code' => 500, 'msg' => '请先完善公司信息']);
		}
		$cmpId = $company->id;
		$arr_index = 0;
		$check_staff = [];
		foreach ($res as $key => $value) {
			if ($key > 0) {
				if (empty($value[0]) && empty($value[1]) && empty($value[2]) && empty($value[3]) && empty($value[4]) && empty($value[5]) && empty($value[6])) {
					break;
				}
				if (empty($value[0]) || empty($value[1])) {
					return response()->json(['code' => 500, 'msg' => '姓名或电话不能为空']);
				}
				$data[$arr_index]['deptId'] = $deptId;
				$data[$arr_index]['cmpId'] = $cmpId;
				$data[$arr_index]['name'] = $value[0];
				$data[$arr_index]['mobile'] = $value[1];
				$data[$arr_index]['email'] = $value[2];
				$data[$arr_index]['position'] = $value[3];
				$data[$arr_index]['employeeNo'] = $value[4];
				$data[$arr_index]['entryTime'] = strtotime($value[5]);
				$data[$arr_index]['remarks'] = $value[6];
				$data[$arr_index]['createdAt'] = time();
				$data[$arr_index]['updatedAt'] = time();
				$check_staff[$arr_index] = $value[1];
				$arr_index++;
			}
		}
		if (empty($data)) {
			return response()->json(['code' => 500, 'msg' => '数据源为空,不能导入']);
		}
		$unique_arr = array_unique($check_staff);
		if (!empty($check_staff) && count($unique_arr) != count($data)) {
			return response()->json(['code' => 500, 'msg' => '导入失败,手机号不能重复']);
		}
		$check_staff_data = Staff::where(['status' => 0, 'cmpId' => $cmpId])->whereIn('mobile', $unique_arr)->first();
		if (!empty($check_staff_data)) {
			return response()->json(['code' => 500, 'msg' => '导入失败,手机号不能重复']);
		}
		$check_staff_data_del = Staff::where(['cmpId' => $cmpId, 'status' => 1])->whereIn('mobile', $unique_arr)->pluck('mobile', 'id');
		//更新已有员工表数据
		$get_data = [];
		DB::beginTransaction();
		try {
			//中间逻辑代码
			if (!empty($check_staff_data_del)) {
				//
				$arr = $check_staff_data_del->toArray();
				$arr_keys = array_keys($arr);
				$arr_values = array_values($arr);
				foreach ($data as $k => $val) {
					if (in_array($val['mobile'], $arr_values)) {
						$get_key = array_search($val['mobile'], $arr_values);
						$ids = $arr_keys[$get_key];
						$val['status'] = 0;
						//更新员工表
						Staff::where('id', $ids)->update($val);
						unset($data[$k]);
					}
				}

			}
			//插入新记录
			DB::table('employeeInfo')->insert($data);
			DB::commit();
			return response()->json(['code' => 200, 'msg' => '导入数据成功']);
		} catch (\Exception $e) {
			//接收异常处理并回滚
			DB::rollBack();
			return response()->json(['code' => 500, 'msg' => '导入数据失败']);
		}
	}
}
